package pack1;

import java.io.IOException;
import java.io.PrintWriter;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.swim.session.FriendshipRemote;

/**
 * Gestisce il login degli utenti
 */
public class FriendshipRequestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
    
    public FriendshipRequestServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	HttpSession session = request.getSession();
    	if(session.getAttribute("authenticated") == null || !(boolean)session.getAttribute("authenticated")) {
    		response.sendRedirect("index.jsp");
			return;
    	}
    }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
    	if(session.getAttribute("authenticated") == null || !(boolean)session.getAttribute("authenticated")) {
    		response.sendRedirect("index.jsp");
			return;
    	}
		try{
				
			String to = request.getParameter("to");
			String from = request.getParameter("from");

			if(from == null || to == null ) {
	    		response.sendRedirect("index.jsp");
			} else {
				//add user to DB
				response.setContentType("text/html");
				
				try {
					InitialContext jndiContext = (InitialContext) Util.getInitialContext();
					Object ref = jndiContext.lookup("FriendshipBeanJNDI");
					FriendshipRemote f = (FriendshipRemote) ref;
					String dirStr = request.getParameter("direct");
					boolean direct = false;
					if(dirStr != null)
						direct = Boolean.parseBoolean(dirStr);
					
					f.newFriendshipRequest(from,to,direct);
					request.setAttribute("title","Friendship Requested");
					request.setAttribute("message","The friendship has been requested. Go <a href=\"profile.jsp?email="+to+"\">back</a> to the profile or <a href=\"index.jsp\">home</a>");
					RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/target.jsp");
					dispatcher.forward(request, response); 
				} catch (NamingException e) {
					e.printStackTrace();
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
			PrintWriter out = response.getWriter();
			out.print("Errore login utente!");
		}
	}
	
}
